import 'dart:async';

import 'package:flutterDemo/database/sqlite_helper.dart';
import 'package:flutterDemo/repository/api.dart';

class DataSyncService {
  final SQLiteHelper dbHelper = SQLiteHelper();
  late Timer _syncTimer;

  void initState() async {
    await dbHelper.database;
    _startSyncTimer();
  }

  void _startSyncTimer() {
    _syncTimer = Timer.periodic(Duration(seconds: 5), (timer) async {
      print("这没走吗");
      await syncData();
    });
  }

  Future<void> syncData() async {
    final data = await dbHelper.queryAll();
    print("能否拿到数据${data}");
    for (var item in data) {
      try {
        final res = await Api.instance.setData();
        print("同步成功啦 ❀❀❀❀❀❀❀❀");
      } catch (e) {
        // 数据同步失败，处理错误
        print(e.toString());
      }
    }
  }

  void dispose() {
    _syncTimer.cancel();
  }
}
